import {
  PageContainer,
  ProCard,
  FooterToolbar,
  ProForm,
  ProFormText,
  ProFormItem,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Button, message, Space } from 'antd';

import PermissionsTree from './permissions-tree';
import { saveOrUpdate, queryRoleDetail } from '@/services/role-management';
import useDetailType from '@/hooks/useDetailType';

const RoleDetail: React.FC = () => {
  // const { validator: brandSelectValidator, BrandSelect } = useBrandSelect();
  const { isModify, isRead, params, goReplace, goBack } = useDetailType<Partial<{ id: string }>>();
  const { id } = params;

  /**
   * 获取角色详情
   * @param roleId
   * @returns
   */
  const getRoleDetail = async (roleId: string) => {
    const res = await queryRoleDetail({ id: roleId });
    if (!res.code && res.data) {
      return res.data;
    }
    return {} as API.RoleDetail;
  };

  /**
   * 提交保存
   * @param value
   * @returns
   */
  const onFinish = async (value: API.RoleDetailParam) => {
    if (isModify && id) {
      value.id = id;
    }
    const res = await saveOrUpdate(value);
    if (!res.code && res.data) {
      message.success('提交成功');
      goReplace('/system/role/list');
      return;
    }
    message.error(res.message || '提交失败');
  };

  /**
   * 初始化
   * @returns
   */
  const init = async () => {
    if ((isModify || isRead) && !!id) {
      return getRoleDetail(id);
    }
    return {} as API.RoleDetail;
  };

  return (
    <PageContainer>
      <ProCard>
        <ProForm<API.RoleDetail>
          layout="horizontal"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 10 }}
          request={init}
          submitter={{
            render: (_, dom) => (
              <FooterToolbar
                extra={
                  <div style={{ textAlign: 'center', padding: '5px 0' }}>
                    {isRead ? (
                      <Button onClick={goBack}>返回</Button>
                    ) : (
                      <Space>
                        <Button onClick={goBack}>返回</Button>
                        {dom[1]}
                      </Space>
                    )}
                  </div>
                }
              />
            ),
          }}
          onFinish={onFinish}
          onValuesChange={(e) => console.log(e)}
        >
          <ProFormText
            name="name"
            label="角色名称"
            tooltip="角色名称长度3-20个字符"
            placeholder="请输入角色名称"
            readonly={isRead}
            required
            rules={[
              {
                required: true,
                message: '请输入角色名称',
              },
              {
                min: 3,
                message: '角色名称长度3-20个字符',
              },
              {
                max: 20,
                message: '角色名称长度3-20个字符',
              },
            ]}
          />

          <ProFormTextArea
            label="角色描述"
            name="roleDesc"
            readonly={isRead}
            allowClear
            rules={[{ max: 99, message: '最多99个字符' }]}
          />

          <ProFormItem
            label="角色权限"
            name="resourceIds"
            required
            rules={[
              {
                validator: (_, value) => {
                  if (!value || !value.length) return Promise.reject(new Error('请选择角色权限'));
                  return Promise.resolve();
                },
              },
            ]}
          >
            <PermissionsTree readonly={isRead} />
          </ProFormItem>
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};

export default RoleDetail;
